import redis
import json

# redis_config = {  # 外网地址
#     'host': 'bj-crs-dbsuxig7.sql.tencentcdb.com',
#     'port': 22237,
#     'username': 'root',
#     'password': 'Ftms@2024',
# }

redis_config = {  # 内网地址
    'host': '172.16.0.3',
    'port': 6379,
    'username': 'root',
    'password': 'Ftms@2024',
}


def connect_redis(db_num):
    redis_db = redis.Redis(
        host=redis_config['host'],
        port=redis_config['port'],
        password=redis_config['password'],
        username=redis_config['username'],
        db=int(db_num)
    )
    return redis_db


# 设置值
def redis_set(num, second, key, value):
    redis_db = connect_redis(num)
    redis_db.setex(key, second, value)  # 过期时间为秒


# 设置值
def redis_set3day(num, key, value):
    redis_db = connect_redis(num)
    redis_db.setex(key, 3 * 24 * 60 * 60, value)  # 过期时间为3天


def redis_set1day(num, key, value):
    redis_db = connect_redis(num)
    redis_db.setex(key, 1 * 24 * 60 * 60, value)  # 过期时间为3天


# 获取
def redis_get(num, key):
    redis_db = connect_redis(num)
    res = redis_db.get(key)
    return res


# 库总量
def redis_get_count(num):
    redis_db = connect_redis(num)
    count = redis_db.dbsize()
    return count


# 存在性
def redis_exists(num, key):
    redis_db = connect_redis(num)
    res = redis_db.exists(key)
    return res


# 存json
def redis_json_set3day(num, key, dic):
    redis_db = connect_redis(num)
    redis_db.setex(key, 3 * 24 * 60 * 60, json.dumps(dic))  # 过期时间为3天


# 存json
def redis_json_set15day(num, key, dic):
    redis_db = connect_redis(num)
    redis_db.setex(key, 15 * 24 * 60 * 60, json.dumps(dic))  # 过期时间为15天


# 存json
def redis_json_set30day(num, key, dic):
    redis_db = connect_redis(num)
    redis_db.setex(key, 30 * 24 * 60 * 60, json.dumps(dic))  # 过期时间为30天


def redis_json_set1day(num, key, dic):
    redis_db = connect_redis(num)
    redis_db.setex(key, 1 * 24 * 60 * 60, json.dumps(dic))  # 过期时间为1天


# 持久存json
def redis_json_permanent(num, key, dic):
    redis_db = connect_redis(num)
    redis_db.set(key, json.dumps(dic))


# 获取json
def redis_json_get(num, key):
    redis_db = connect_redis(num)
    res = redis_db.get(key)
    if res is None:
        return None
    else:
        return json.loads(res)


def hash_set(num, key, field, value):
    redis_db = connect_redis(num)
    redis_db.hset(key, field, value)


def hash_get(num, key, field):
    redis_db = connect_redis(num)
    res = redis_db.hget(key, field)
    return res

# 库信息使用情况：
# 0 access_token_gzh
# 1 access_token  小程序
# 2
# 3
# 4 奖品
# 5
# 6
# 7  销售线索1
# 8  销售线索2
# 9  销售线索3
# 10 销售线索4
# 11 当前中奖锁
# 12 单独记中奖
# 13 中奖留资
# 14 抽奖结果1--012
# 15 抽奖结果2--345
# 16 抽奖结果3--678
# 17 抽奖结果4--9AB
# 18 抽奖结果5--CD
# 19 抽奖结果6--EF
